import os
import zipfile
from pathlib import Path

from docx import Document

from base.RAG_da_bang.re_utils import re_anonymize_all


def scan_files(root_dir, extensions=None, max_depth=None):
    """
    递归扫描多层子目录中的文件
    :param root_dir: 根目录路径
    :param extensions: 允许的文件扩展名列表(如['.txt', '.csv'])，None表示所有文件
    :param max_depth: 最大扫描深度，None表示无限制
    :return: 文件路径生成器
    """
    root_path = Path(root_dir)
    if not root_path.exists():
        raise FileNotFoundError(f"目录不存在: {root_dir}")

    for item in root_path.rglob('*'):
        if not item.is_file():
            continue

        # 检查文件扩展名
        if extensions and item.suffix.lower() not in [ext.lower() for ext in extensions]:
            continue

        # 检查目录深度
        if max_depth is not None:
            depth = len(item.relative_to(root_path).parts) - 1
            if depth > max_depth:
                continue
        yield item.absolute()


def read_word(word_path, idx):
    # doc = Document(word_path)
    # for i, para in enumerate(doc.paragraphs):
    #     for run in para.runs:
    #         if run._element.xpath('.//pic:pic',
    #                               namespaces={'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture'}):
    #             print("段落图片", f"段落{i + 1}")
    # 解压 .docx 文件（本质是 ZIP）
    output_dir = r'E:\遇到的问题'
    os.makedirs(output_dir, exist_ok=True)
    bo_flag = False
    with zipfile.ZipFile(word_path, 'r') as zip_ref:
        # 遍历 ZIP 文件中的所有文件
        for file_info in zip_ref.infolist():
            # 图片存储在 word/media/ 目录下
            if file_info.filename.startswith('word/media/'):
                # 提取图片文件名
                image_name = os.path.basename(file_info.filename)
                if image_name:
                    # # 保存到输出目录
                    zip_ref.extract(file_info, output_dir + '\\' + str(idx))
                    # # 重命名文件（避免路径问题）
                    # extracted_path = os.path.join(output_dir, file_info.filename)
                    # target_path = os.path.join(output_dir + '\\' + str(idx), image_name)
                    # os.rename(extracted_path, target_path)
                    # print(f"提取图片: {image_name}")
                    bo_flag = True
                    # print(word_path)
    if bo_flag:
        print(idx, word_path)

if __name__ == '__main__':
    try:
        dir_path = r'D:\工作\IT公司RAG打榜比赛营销相关数据需求\china_mobile_docs_anonymize'
        exts = '.docx'
        extensions = [ext.strip() for ext in exts.split(',')] if exts else None
        print(extensions)

        print("\n扫描结果:")
        for idx, file in enumerate(scan_files(dir_path, extensions, max_depth=5), 1):
            # print(f"{idx:>4}. {file}")
            try:
                read_word(file,idx)
            except Exception as e:
                print(f"错误: {e}")
        # read_word(r'D:\工作\IT公司RAG打榜比赛营销相关数据需求\china_mobile_docs_anonymize\云南\承诺保底享家庭畅享包活动知识库文档.docx', 1)
    except Exception as e:
        print(f"错误: {e}")
